package cn.thr.pethome.user.controller;

import cn.thr.pethome.user.domain.User;
import cn.thr.pethome.user.domain.UserVO;
import cn.thr.pethome.user.query.UserQuery;
import cn.thr.pethome.user.service.IUserService;
import cn.thr.pethome.util.AjaxResult;
import cn.thr.pethome.util.BusinessException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(value = "用户的API",description="用户相关的CRUD功能")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if( user.getId()!=null){
                userService.update(user);
            }
            else{
                userService.add(user);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public User get(@PathVariable("id")Long id)
    {
        return userService.findOne(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<User> list(){

        return userService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public AjaxResult json(@RequestBody UserQuery query) {

        try {
            //获取到当前页
            List<User> byQuery = userService.findByQuery(query);
            //这是获取到总条数
            Long count = userService.findByQueryCount(query);
            return AjaxResult.success().setData(byQuery).setTotal(count);
            //setData 用来返回数据的   setTotal 用来返回总条数
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @PostMapping("/phoneCodeLogin")
    public AjaxResult phoneCodeLogin(@RequestBody UserVO uservo){
        try {
            return userService.phoneCodeLogin(uservo);
        }catch (BusinessException e){
            return AjaxResult.error().setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请稍后再试！！！！");
        }

    }
}
